package com.ocom.human.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ocom.common.entity.human.EntityDeptInfo;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.entity.typehandler.PersonInfoHandle;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.common.request.human.*;
import com.ocom.common.request.wx.UserInfoPageUpdateUserRequest;
import com.ocom.common.request.wx.UserPageAddUserRequest;
import com.ocom.common.utils.AES;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.MD5;
import com.ocom.common.utils.StringUtils;
import com.ocom.common.vo.PersonVo;
import com.ocom.common.vo.human.*;
import com.ocom.common.vo.webapi.UpdateAccessVo;
import com.ocom.human.dao.IDaoDeptInfo;
import com.ocom.human.dao.IDaoPersonnelInfo;
import com.ocom.human.feignclient.WebApiClient;
import com.ocom.human.service.PersonnelInfoService;
import com.ocom.human.service.WechatPerInfoService;
import com.ocom.mysql.aspect.DataSourceAspect;
import icu.mhb.mybatisplus.plugln.base.service.impl.JoinServiceImpl;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Slf4j
@Service
public class PersonnelInfoServiceImpl extends JoinServiceImpl<IDaoPersonnelInfo, EntityPersonnelInfo> implements PersonnelInfoService {

    Logger logger = LoggerFactory.getLogger(PersonnelInfoServiceImpl.class);

    @Autowired
    private WebApiClient webApiClient;


    //注入deptInfo 持久层
    @Autowired
    private IDaoDeptInfo daoDeptInfo;

    //personnelInfo 持久层
    @Autowired
    private IDaoPersonnelInfo personnelInfo;

    @Autowired
    private WechatPerInfoService wechatPerInfoService;

    /**
     * 获取人员列表
     */
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public List<UserInfoYkmVo> PersonnelGetPersonInfo(UserInfoVo userInfoVo, Long comId) {
        //根据传参判断是否为空求出 entityCompanyLists


        return personnelInfo.PersonnelGetPersonInfo(userInfoVo.getComId(), userInfoVo.getPId(), userInfoVo.getDeptId(),
                userInfoVo.getParentDeptID(), userInfoVo.getPName(), userInfoVo.getPCode(), userInfoVo.getPType(),
                userInfoVo.getPPhone(), userInfoVo.getPIden());
    }


    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.MASTER)
    @Transactional
    @Override
    public EntityPersonnelInfo AddPerson(PersonVo personVo, Long comId) {
        EntityPersonnelInfo entityPersonnelInfo = new EntityPersonnelInfo();
        if (StringUtils.isNotNull(personVo.getComId())) {
            entityPersonnelInfo.setComId(personVo.getComId());
        }
        if (StringUtils.isNotNull(personVo.getDeptId())) {
            entityPersonnelInfo.setDeptId(personVo.getDeptId());
        }
        if (StringUtils.isNotNull(personVo.getPName())) {
            entityPersonnelInfo.setPName(personVo.getPName());
        }
        if (StringUtils.isNotNull(personVo.getPCode())) {
            entityPersonnelInfo.setPCode(personVo.getPCode());
        }
        if (StringUtils.isNotNull(personVo.getPPwd())) {
            entityPersonnelInfo.setPPwd(personVo.getPPwd());
        }else{
            
        }
        if (StringUtils.isNotNull(personVo.getPType())) {
            entityPersonnelInfo.setPType(personVo.getPType());
        }
        if (StringUtils.isNotNull(personVo.getPSex())) {
            entityPersonnelInfo.setPSex(personVo.getPSex());
        }
        if (StringUtils.isNotNull(personVo.getPPhone())) {
            entityPersonnelInfo.setPPhone(personVo.getPPhone());
        }
        if (StringUtils.isNotNull(personVo.getPIdentity())) {
            entityPersonnelInfo.setPIdentity(personVo.getPIdentity());
        }
        if (StringUtils.isNotNull(personVo.getPBorn())) {
            entityPersonnelInfo.setPBorn(personVo.getPBorn());
        }
        if (StringUtils.isNotNull(personVo.getPAddress())) {
            entityPersonnelInfo.setPAddress(personVo.getPAddress());
        }
        if (StringUtils.isNotNull(personVo.getPPhotoUrl())) {
            entityPersonnelInfo.setPPhotoUrl(personVo.getPPhotoUrl());
        }
        if (StringUtils.isNotNull(personVo.getStatus())) {
            entityPersonnelInfo.setStatus(personVo.getStatus());
        }
        if (StringUtils.isNotEmpty(personVo.getEncryIdentity())) {
            entityPersonnelInfo.setEncryIdentity(personVo.getEncryIdentity());
        }
        if (StringUtils.isNotEmpty(personVo.getEncryPhone())) {
            entityPersonnelInfo.setEncryPhone(personVo.getEncryPhone());
        }
//        if (!CommonUtil.isNull(personVo.getPTags())) {
//            entityPersonnelInfo.setPTags(personVo.getPTags());
//        }
        if (StringUtils.isNotNull(personVo.getBankNo())) {
            entityPersonnelInfo.setBankNo(personVo.getBankNo());
        }
        personnelInfo.insert(entityPersonnelInfo);
        return entityPersonnelInfo;
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.MASTER)
    @Transactional
    @Override
    public EntityPersonnelInfo UpdatePerson(PersonVo personVo, Long comId) {
        EntityPersonnelInfo entityPersonnelInfo = new EntityPersonnelInfo();
//        if (StringUtils.isNotNull(personVo.getComId())) {
//            entityPersonnelInfo.setComId(personVo.getComId());
//        }
        if (StringUtils.isNotNull(personVo.getDeptId())) {
            entityPersonnelInfo.setDeptId(personVo.getDeptId());
        }
        if (StringUtils.isNotNull(personVo.getPName())) {
            entityPersonnelInfo.setPName(personVo.getPName());
        }
        if (StringUtils.isNotNull(personVo.getPCode())) {
            entityPersonnelInfo.setPCode(personVo.getPCode());
        }
        if (StringUtils.isNotNull(personVo.getPPwd())) {

            entityPersonnelInfo.setPPwd(personVo.getPPwd());
        }
        if (StringUtils.isNotNull(personVo.getPType())) {
            entityPersonnelInfo.setPType(personVo.getPType());
        }
        if (StringUtils.isNotNull(personVo.getPSex())) {
            entityPersonnelInfo.setPSex(personVo.getPSex());
        }
        if (!CommonUtil.isNull(personVo.getPPhone())) {
            entityPersonnelInfo.setEncryPhone(CommonUtil.encryptPhone(personVo.getPPhone()));
            entityPersonnelInfo.setPPhone(personVo.getPPhone());
        }
        if (!CommonUtil.isNull(personVo.getPIdentity())) {
            entityPersonnelInfo.setEncryIdentity(CommonUtil.encryptIdCard(personVo.getPIdentity()));
            entityPersonnelInfo.setPIdentity(personVo.getPIdentity());
        }
        if (StringUtils.isNotNull(personVo.getPBorn())) {
            entityPersonnelInfo.setPBorn(personVo.getPBorn());
        }
        if (StringUtils.isNotNull(personVo.getPAddress())) {
            entityPersonnelInfo.setPAddress(personVo.getPAddress());
        }
        if (StringUtils.isNotNull(personVo.getPPhotoUrl())) {
            entityPersonnelInfo.setPPhotoUrl(personVo.getPPhotoUrl());
        }
        if (StringUtils.isNotNull(personVo.getStatus())) {
            entityPersonnelInfo.setStatus(personVo.getStatus());
        }
        if (StringUtils.isNotNull(personVo.getPId())) {
            entityPersonnelInfo.setPId(personVo.getPId());
        }
//        if (StringUtils.isNotEmpty(personVo.getEncryIdentity())) {
//            entityPersonnelInfo.setEncryIdentity(personVo.getEncryIdentity());
//        }
//        if (StringUtils.isNotEmpty(personVo.getEncryPhone())) {
//
//            entityPersonnelInfo.setEncryPhone(personVo.getEncryPhone());
//        }
        if (StringUtils.isNotNull(personVo.getBankNo())) {
            entityPersonnelInfo.setBankNo(personVo.getBankNo());
        }
//        if (!CommonUtil.isNull(personVo.getPTags())) {
//            entityPersonnelInfo.setPTags(personVo.getPTags());
//        }
        personnelInfo.updateById(entityPersonnelInfo);
        return personnelInfo.selectById(entityPersonnelInfo);
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId")
    @Override
    public List<EntityPersonnelInfo> GetPersonInfo(Long comId, Long deptId) {
        QueryWrapper<EntityPersonnelInfo> queryWrapper = new QueryWrapper<>();
        if (deptId == null || deptId == 0L) {
            queryWrapper.eq("com_id", comId);
        } else {
            queryWrapper.eq("dept_id", deptId);
        }
        return this.list(queryWrapper);
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public EntityPersonnelInfo GetPersonInfo(Long comId, PersonnelGetPersoDecryVo personnelGetPersoDecryVo) {

        if(CommonUtil.isNull(personnelGetPersoDecryVo.getPPhone()) && CommonUtil.isNull(personnelGetPersoDecryVo.getPIdentity()) ){
            return null;
        }
        QueryWrapper<EntityPersonnelInfo> query = Wrappers.query();
        query.eq("com_id", comId);
        query.eq("status", 0);
        if (StringUtils.isNotEmpty(personnelGetPersoDecryVo.getPIdentity())) {
            query.eq("p_identity", PersonInfoHandle.encryptS(personnelGetPersoDecryVo.getPIdentity()) );
        }
        if (StringUtils.isNotEmpty(personnelGetPersoDecryVo.getPPhone())) {
            query.eq("p_phone",  PersonInfoHandle.encryptS(personnelGetPersoDecryVo.getPPhone()) );
        }
        query.last("limit 1");
        return personnelInfo.selectOne(query);
    }


    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.SLAVE)
    public UserInfoYkmVo getPersonInfoById(Long comId, Long pId) {
        return personnelInfo.getPersonInfoById(comId, pId);
    }

    @Override
    public EntityPersonnelInfo GetPersonnelNoDesensitized(Long comId, Long pId) {
        QueryWrapper<EntityPersonnelInfo> query = Wrappers.query();
        query.eq("com_id", comId);
        query.eq("p_id", pId);
        return personnelInfo.selectOne(query);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.SLAVE)
    public EntityPersonnelInfo getPersonInfoOne(Long comId, Long pId) {
        return this.getById(pId);
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId")
    @Override
    public EntityPersonnelInfo getPersonInfopIdentity(Long comId, String identity) {
        QueryWrapper<EntityPersonnelInfo> query = Wrappers.query();
        query.eq("com_id", comId);
        query.eq("p_identity", PersonInfoHandle.encryptS(identity) );
        query.eq("status", 0);
        query.last("limit 1");
        return baseMapper.selectOne(query);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId")
    public EntityPersonnelInfo getPersonInfopPhone(Long comId, String phone) {
        QueryWrapper<EntityPersonnelInfo> query = Wrappers.query();
        query.eq("com_id", comId);
        query.eq("p_phone", PersonInfoHandle.encryptS(phone));
        query.eq("status", 0);
        query.last("limit 1");
        return baseMapper.selectOne(query);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB)
    public EntityPersonnelInfo regexpPerson(Long companyId, String name, String phone, String pIdentity) {
        QueryWrapper<EntityPersonnelInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("com_id", companyId);
        name = name.replace("*", "_");
        phone = phone.replace("*", "_");
        pIdentity = pIdentity.replace("*", "_");
        queryWrapper.like("p_name", name);
        queryWrapper.eq("p_phone", PersonInfoHandle.encryptS(phone) );
        queryWrapper.eq("p_identity", PersonInfoHandle.encryptS(pIdentity)  );
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB)
    @Override
    public EntityPersonnelInfo updateUser(Long companyId, UserInfoPageUpdateUserRequest request) {
        UpdateWrapper<EntityPersonnelInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("p_id", request.getUserId());
        updateWrapper.set("dept_id", request.getDeptId());
        updateWrapper.set("p_phone", PersonInfoHandle.encryptS(request.getTelephone()) );
        updateWrapper.set("p_identity", PersonInfoHandle.encryptS(request.getIdentity()));

        updateWrapper.set("encry_phone", CommonUtil.encryptPhone(request.getTelephone()) );
        updateWrapper.set("encry_identity", CommonUtil.encryptIdCard(request.getIdentity()));

        updateWrapper.set("p_name", request.getUserName());
        updateWrapper.set("update_time", new Date());
        this.update(updateWrapper);
        return this.getById(request.getUserId());
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.MASTER)
    @Override
    public void updateUser(Long comId, EntityPersonnelInfo entityPersonnelInfo) {
        try {
            entityPersonnelInfo.setPCode(null);
            if (CommonUtil.isNull(entityPersonnelInfo.getPIdentity())) {
                entityPersonnelInfo.setPIdentity(null);
            }
        } catch (Exception e) {

        }
        try {
            if (CommonUtil.isNull(entityPersonnelInfo.getPPhotoUrl())) {
                entityPersonnelInfo.setPPhotoUrl(null);
            }
        } catch (Exception e) {

        }
        try {
            if (CommonUtil.isNull(entityPersonnelInfo.getPPhone())) {
                entityPersonnelInfo.setPPhone(null);
            }
        } catch (Exception e) {

        }
        personnelInfo.updateById(entityPersonnelInfo);
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB)
    @Override
    public EntityPersonnelInfo updateUserStatus(Long companyId, Long pId, Integer state) {
        UpdateWrapper<EntityPersonnelInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("p_id", pId);
        updateWrapper.set("status", state);
        this.update(updateWrapper);
        return this.getById(pId);
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB)
    @Override
    public EntityPersonnelInfo addPerUser(Long companyId, UserPageAddUserRequest request) {
        QueryWrapper<EntityPersonnelInfo> entityPersonnelInfoQueryWrapper = new QueryWrapper<>();
        entityPersonnelInfoQueryWrapper.eq("p_phone", request.getTelephone());
        entityPersonnelInfoQueryWrapper.eq("com_id", companyId);
        entityPersonnelInfoQueryWrapper.last("limit 1");
        EntityPersonnelInfo personnelInfo = this.getOne(entityPersonnelInfoQueryWrapper);
        if (personnelInfo != null) {
            return personnelInfo;
        }
        EntityPersonnelInfo entityPersonnelInfo = new EntityPersonnelInfo();
        entityPersonnelInfo.setComId(request.getCompanyId());
        entityPersonnelInfo.setPName(request.getUserName());
        if (request.getDeptId() != null && request.getDeptId() > 0) {
            entityPersonnelInfo.setDeptId(request.getDeptId());
        }
        if (request.getIdentity() != null && !request.getIdentity().isEmpty()) {
            entityPersonnelInfo.setPIdentity(request.getIdentity());
            entityPersonnelInfo.setEncryIdentity(CommonUtil.encryptIdCard(request.getIdentity()));
        }
        if (request.getTelephone() != null && !request.getTelephone().isEmpty()) {
            entityPersonnelInfo.setPPhone(request.getTelephone());
            entityPersonnelInfo.setEncryPhone(CommonUtil.encryptPhone(request.getTelephone()));
        }
        if (request.getPCode() != null && !request.getPCode().isEmpty()) {
            entityPersonnelInfo.setPCode(request.getPCode());
        }
        this.save(entityPersonnelInfo);
        return entityPersonnelInfo;

    }

    /**
     * 检验人员是否存在
     *
     * @return
     */
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId")
    @Override
    public EntityPersonnelInfo pCodeUnique(Long comId, String pCode) {
        QueryWrapper<EntityPersonnelInfo> query = Wrappers.query();
        if (StringUtils.isNotNull(comId)) {
            query.eq("com_id", comId);
        }
        if (StringUtils.isNotEmpty(pCode)) {
            query.eq("p_code", pCode);
        }
        query.eq("status", 0);
        query.orderByDesc("create_time");
        query.last("limit 1");
        return personnelInfo.selectOne(query);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB)
    public boolean existPerson(Long companyId, String phone, String idCard) {
        QueryWrapper<EntityPersonnelInfo> query = Wrappers.query();
        query.eq("com_id", companyId);
        query.eq("p_phone", PersonInfoHandle.encryptS(phone) ).or().eq("p_identity", PersonInfoHandle.encryptS(idCard) );
        query.eq("status", 0);
        query.orderByDesc("create_time");
        query.last("limit 1");
        EntityPersonnelInfo entityPersonnelInfo = this.getOne(query);
        return entityPersonnelInfo != null ? true : false;
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB)
    public boolean removePerson(Long companyId, Long pId, Long userId) {
        //    System.out.println(companyId);
        //    System.out.println(userId);
        logger.info("移除人员:" + companyId.toString() + ",userId:" + userId.toString());

        /**
         * 业务逻辑：WEB端、小程序端删除人员时都调用这个接口，修改人员状态为离职(personnel_info.status=1，where条件：personnel_info.p_id=请求参数pid，personnel.com_id=请求参数comID)，并且删除微信用户(where条件：wechat_per_info.p_id=请求参数pid，wechat_per_info.com_id=请求参数comID)
         */
        UpdateWrapper<EntityPersonnelInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("p_id", userId);
        updateWrapper.set("status", 1);
        updateWrapper.set("update_time", new Date());
        return this.update(updateWrapper);
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId")
    @Override
    public EntityPersonnelInfo ImportUserInfo(Long comId, EntityPersonnelInfo personnelInfo) {
        this.save(personnelInfo);
        return personnelInfo;
    }

    /**
     * 获取人员加密信息（加密》解密）	personnel/getPersoDecry
     *
     * @return
     */
//    @Override
//    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.SLAVE)
//    public EntityPersonnelInfo PersonnelGetPersoDecry(Long comId, PersonnelGetPersoDecryVo personnelGetPersoDecryVo) {
//        QueryWrapper<EntityPersonnelInfo> query = Wrappers.query();
//        query.eq("com_id", comId);
//        query.eq("status", 0);
//        if (StringUtils.isNotEmpty(personnelGetPersoDecryVo.getPIdentity())) {
//            query.eq("p_identity", PersonInfoHandle.encryptS(personnelGetPersoDecryVo.getPIdentity()) );
//        }
//        if (StringUtils.isNotEmpty(personnelGetPersoDecryVo.getPPhone())) {
//            query.eq("p_phone", PersonInfoHandle.encryptS(personnelGetPersoDecryVo.getPPhone()) );
//        }
//        query.last("limit 1");
//        return personnelInfo.selectOne(query);
//    }

    /**
     * 查找对应的学生信息
     *
     * @return
     */
    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityPersonnelInfo> getPersonInfopCode(Long comId, List<String> pCode) {
        QueryWrapper<EntityPersonnelInfo> query = Wrappers.query();
        query.eq("com_id", comId);
        query.in("p_code", pCode);
        return personnelInfo.selectList(query);
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId")
    @Override
    public boolean updateStudentInfo(Long comId, JSONObject jsonObject) {
        UpdateWrapper<EntityPersonnelInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("region_online", jsonObject.getLong("regionOnline"));
        updateWrapper.set("region_id", jsonObject.getLong("regionId"));
        updateWrapper.set("update_time", new Date());
        updateWrapper.eq("com_id", comId);
        updateWrapper.eq("p_id", jsonObject.getLong("pid"));
        return this.update(updateWrapper);
    }

    /**
     * 更改人员人脸图片（/updateUserFace）
     */
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.MASTER)
    @Override
    public void updateUserFace(Long comId, UpdateUserFaceVo updateUserFaceVo) {
        UpdateWrapper<EntityPersonnelInfo> query = Wrappers.update();
        query.eq("com_id", updateUserFaceVo.getComId());

        UpdateAccessVo updateAccessVo = new UpdateAccessVo();
        updateAccessVo.setComId(updateUserFaceVo.getComId());
        if (updateUserFaceVo.getType().equals(1)) {
            query.eq("p_name", updateUserFaceVo.getParam());
            query.set(" p_photo_url", updateUserFaceVo.getPPhotoUrl());
            updateAccessVo.setType(2);
            updateAccessVo.setUserName(updateUserFaceVo.getParam());
        }
        if (updateUserFaceVo.getType().equals(2)) {
            query.eq("p_code", updateUserFaceVo.getParam());
            query.set(" p_photo_url", updateUserFaceVo.getPPhotoUrl());
            updateAccessVo.setType(1);
            updateAccessVo.setPCode(updateUserFaceVo.getParam());
        }
        if (updateUserFaceVo.getType().equals(3)) {
            String key = MD5.MD5Encode(updateUserFaceVo.getComId().toString(), "utf8");
            String identity = AES.encrypt(updateUserFaceVo.getParam(), key);
            query.eq(" encry_identity", identity);
            query.set(" p_photo_url", updateUserFaceVo.getPPhotoUrl());
            updateAccessVo.setType(3);
            updateAccessVo.setIdentity(updateUserFaceVo.getParam());
        }

        if (updateAccessVo.getType() != null && updateAccessVo.getType() > 0) {
            try {
                webApiClient.updateUserAccess(updateAccessVo);
            } catch (Exception e) {
                log.info("人员更新權限異常:{{}}", e);
            }
        }

        this.update(query);
    }

    /**
     * 更改人员人脸图片（/updateUserFace）
     */
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public EntityPersonnelInfo getUserFace(Long comId, UpdateUserFaceVo updateUserFaceVo) {
        QueryWrapper<EntityPersonnelInfo> query = Wrappers.query();
        query.eq("com_id", updateUserFaceVo.getComId());

        if (updateUserFaceVo.getType().equals(1)) {
            query.eq("p_name", updateUserFaceVo.getParam());
        }
        if (updateUserFaceVo.getType().equals(2)) {
            query.eq("p_code", updateUserFaceVo.getParam());
        }
        if (updateUserFaceVo.getType().equals(3)) {
//            String key = MD5.MD5Encode(updateUserFaceVo.getComId().toString(), "utf8");
//            String identity = AES.encrypt(updateUserFaceVo.getParam(), key);
            query.eq("p_identity", PersonInfoHandle.encryptS(updateUserFaceVo.getParam()) );
        }
        query.last("limit 1");

        return this.getOne(query);
    }

    // 人员列表查询（getPersonnelList）
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public List<UserListRVo> GetPersonnelList(Long comId, UserListVo userListVo) {
        PageHelper.startPage(userListVo.getPage(), userListVo.getSize());
        List<Integer> tagIds = new ArrayList<>();
        Set groupNoCount = new HashSet();
        List<UserListVo.PTags> pTags = userListVo.getPTags();

        if (null != pTags) {
            for (UserListVo.PTags pTag : pTags) {
                tagIds.add(pTag.getTagId());
                groupNoCount.add(pTag.getGroupNo());
            }
        }
        
        List<UserListRVo> userListRVos = personnelInfo.GetPersonnelList(userListVo.getComId(), userListVo.getPId(), userListVo.getDeptId(),
                userListVo.getParentDeptId(), userListVo.getPName(), userListVo.getPCode(), userListVo.getPType(),
                userListVo.getPPhone(), userListVo.getPIdentity(), userListVo.getStatus(), userListVo.getAccountState(),new Date(),tagIds, groupNoCount.size(),userListVo.getCardNo(),userListVo.getBankNo());

        return userListRVos;
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.SLAVE)
    public XfUserInfoVo getXfUserInfo(Long comId, Long pId) {
        XfUserInfoVo xfUserInfoVo = personnelInfo.getXfUserInfo(comId, pId);
        return xfUserInfoVo;
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.MASTER)
    public Boolean modifyPwd(Long companyId, PersonVo personVo) {
        UpdateWrapper<EntityPersonnelInfo> updateWrapper = Wrappers.update();
        updateWrapper.eq("p_id", personVo.getPId());
        updateWrapper.set("p_pwd",PersonInfoHandle.encryptS(personVo.getPPwd()) );
        return this.update(updateWrapper);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.MASTER)
    public Boolean modifyPhoto(Long companyId, PersonVo personVo) {
        UpdateWrapper<EntityPersonnelInfo> updateWrapper = Wrappers.update();
        updateWrapper.eq("p_id", personVo.getPId());
        updateWrapper.set("p_photo_url2", personVo.getPPhotoUrl2());
        if(!CommonUtil.isNull(personVo.getPPhotoUrl()))  updateWrapper.set("p_photo_url", personVo.getPPhotoUrl());
        return this.update(updateWrapper);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.SLAVE)
    public Integer checkUnique(Long companyId, String code, String phone) {
        QueryWrapper<EntityPersonnelInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("com_id", companyId);
        if (!CommonUtil.isNull(code)) {
            queryWrapper.eq("p_code", code);
        }
        if (!CommonUtil.isNull(phone)) {
            queryWrapper.eq("p_phone", PersonInfoHandle.encryptS(phone) );
//            String phone1 = PersonPhoneHandle.staticEncrypt(phone, companyId);
//            queryWrapper.and(wrapper -> {
//                wrapper.or().eq("encry_phone", phone1).or().eq("p_phone", phone);
//            });
        }
        return this.count(queryWrapper);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.SLAVE)
    public UserInfoByNamePhoneVo getPinfoByNameAndCode(Long comId, String pName, String pCode) {
        return personnelInfo.getPinfoByNameAndCode(comId, pName, pCode);
    }


    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.SLAVE)
    public EntityPersonnelInfo getPersonInfo(Long companyId, UserInfoVo userInfoVo) {
        QueryWrapper<EntityPersonnelInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("com_id", companyId);
        queryWrapper.eq("status", 0);
        if (!CommonUtil.isNull(userInfoVo.getPCode())) {
            queryWrapper.eq("p_code", userInfoVo.getPCode());
        }
        if (userInfoVo.getPId() != null) {
            queryWrapper.eq("p_id", userInfoVo.getPId());
        }
        if (!CommonUtil.isNull(userInfoVo.getPName())) {
            queryWrapper.eq("p_name", userInfoVo.getPName());
        }
        if (!CommonUtil.isNull(userInfoVo.getPPhone())) {
            queryWrapper.eq("p_phone", PersonInfoHandle.encryptS(userInfoVo.getPPhone()) );
//            String phone1 = PersonPhoneHandle.staticEncrypt(userInfoVo.getPPhone(), companyId);
//            queryWrapper.and(wrapper -> {
//                wrapper.or().eq("encry_phone", phone1).or().eq("p_phone", userInfoVo.getPPhone());
//            });
        }
        queryWrapper.orderByDesc("create_time");
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }


    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.SLAVE)
    public EntityPersonnelInfo getPersonInfoByStatus(Long companyId, UserInfoVo userInfoVo) {
        QueryWrapper<EntityPersonnelInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("com_id", companyId);
        if (userInfoVo.getStatus() != null) {
            queryWrapper.eq("status", userInfoVo.getStatus());
        }
        if (!CommonUtil.isNull(userInfoVo.getPCode())) {
            queryWrapper.eq("p_code", userInfoVo.getPCode());
        }
        if (userInfoVo.getPId() != null) {
            queryWrapper.eq("p_id", userInfoVo.getPId());
        }
        if (!CommonUtil.isNull(userInfoVo.getPName())) {
            queryWrapper.eq("p_name", userInfoVo.getPName());
        }
        if (!CommonUtil.isNull(userInfoVo.getPPhone())) {
            queryWrapper.eq("p_phone", PersonInfoHandle.encryptS(userInfoVo.getPPhone()) );
//            String phone1 = PersonPhoneHandle.staticEncrypt(userInfoVo.getPPhone(), companyId);
//            queryWrapper.and(wrapper -> {
//                wrapper.or().eq("encry_phone", phone1).or().eq("p_phone", userInfoVo.getPPhone());
//            });
        }
        queryWrapper.orderByDesc("create_time");
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityPersonnelInfo> getPersonInfoGtPId(Long companyId, UserInfoVo userInfoVo) {
        QueryWrapper<EntityPersonnelInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("com_id", companyId);
        if (userInfoVo.getStatus() != null) {
            queryWrapper.eq("status", userInfoVo.getStatus());
        }
        if (userInfoVo.getStartPid() != null) {
            queryWrapper.gt("p_id", userInfoVo.getStartPid());
        }
        if (userInfoVo.getSize() != null) {
            queryWrapper.last("limit " + userInfoVo.getSize());
        }
        queryWrapper.orderByAsc("p_id");

        return this.list(queryWrapper);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE)
    public List<PersonQueryVo> getPersonInfoByCardNoAndP(Long companyId, Integer pId, String pCode, String pName, String cardNo) {
        return personnelInfo.getPersonInfoByCardNoAndP(companyId, pId, pCode, pName, cardNo);
    }


    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.SLAVE)
    public List<PersonBornVo> getPersonAccountByBorn(Long companyId,Integer accType ,String pBorn) {
        return personnelInfo.getPersonAccountByBorn(companyId, accType, pBorn);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityPersonnelInfo> getPersonByPCodes(Long companyId, List<String> pCodes) {
        return this.list(Wrappers.lambdaQuery(EntityPersonnelInfo.class).eq(EntityPersonnelInfo::getComId,companyId).in(EntityPersonnelInfo::getPCode,pCodes));
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityPersonnelInfo> getPersonByIds(Long companyId, List<Long> pIds) {
        return this.list(Wrappers.lambdaQuery(EntityPersonnelInfo.class).eq(EntityPersonnelInfo::getComId,companyId).in(EntityPersonnelInfo::getPId,pIds));
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.MASTER)
    public boolean updateUserRegion(Long companyId, UpdateUserRegionRequest request) {
        UpdateWrapper<EntityPersonnelInfo> updateWrapper = Wrappers.update();
        updateWrapper.eq("p_id", request.getPId());
        updateWrapper.eq("com_id", request.getComId());
        if(request.getRegionId()!=null)  updateWrapper.set("region_id", request.getRegionId());
        if(request.getRegionOnline()!=null)  updateWrapper.set("region_online", request.getRegionOnline());
        if(request.getType()==1 && request.getRegionOrigId()!=null){
            updateWrapper.le("region_orig_id", request.getRegionOrigId());
            updateWrapper.set("region_orig_id", request.getRegionOrigId());
        }
        return this.update(updateWrapper);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.SLAVE)
    public List<KqStudentVo>  getKqAndStudentsOnline(Long companyId, StudentsOnlineRequest request) {
        JoinLambdaWrapper<EntityPersonnelInfo> queryWrapper = new JoinLambdaWrapper<>(EntityPersonnelInfo.class);
        queryWrapper.selectAs((cb) -> {
            cb.add(" personnel_info.dept_id ","deptId",false);
            cb.add(" personnel_info.region_online ","state",false);
            cb.add(" count(*)  ","students",false);
        });
        queryWrapper.eq(EntityPersonnelInfo::getComId, companyId);
        queryWrapper.eq(EntityPersonnelInfo::getStatus, 0);
        if (request.getDeptIds().size() >0) {
            queryWrapper.in(EntityPersonnelInfo::getDeptId , request.getDeptIds());
        };

        queryWrapper.notDefaultSelectAll().leftJoin(EntityDeptInfo.class, EntityDeptInfo::getDeptId, EntityPersonnelInfo::getDeptId)
                .selectAs((cb) -> {
                    cb.add(" dept_info.dept_name ","deptName",false);
                })
                .end();

        queryWrapper.groupBy(EntityPersonnelInfo::getDeptId,EntityPersonnelInfo::getRegionOnline);
        return this.joinList(queryWrapper,KqStudentVo.class);

    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.SLAVE)
    public PageInfo<EntityPersonnelInfo>  getKqAndStudentsDetail(Long companyId, StudentsDetailRequest request) {
        QueryWrapper<EntityPersonnelInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("com_id", companyId);
        queryWrapper.eq("status", 0);
        if(request.getRegionOnline()!=null) queryWrapper.eq("region_online", request.getRegionOnline());
        if (request.getDeptIds().size() >0) {
            queryWrapper.in("dept_id " , request.getDeptIds());
        }
        PageHelper.startPage(request.getPage(), request.getSize());
        List<EntityPersonnelInfo> pointInfoPageInfo = this.list(queryWrapper);
        return   new PageInfo<>(pointInfoPageInfo);

    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.SLAVE)
    public PageInfo<EntityPersonnelInfo>  getKqAndStudentsDetail2(Long companyId, StudentsDetailRequest request) {
        QueryWrapper<EntityPersonnelInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("p_id","com_id","p_pwd" );
 //       queryWrapper.select("p_id","com_id","p_pwd" ,"p_phone","p_identity","encry_phone","encry_identity","bank_no");
//        queryWrapper.eq("com_id",52);
        PageHelper.startPage(request.getPage(), request.getSize());
        List<EntityPersonnelInfo> pointInfoPageInfo = this.list(queryWrapper);
        return   new PageInfo<>(pointInfoPageInfo);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.MASTER)
    public boolean updateById(Long companyId, EntityPersonnelInfo personnelInfo) {
        return this.updateById(personnelInfo);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityPersonnelInfo> getUserListBypIds(Long companyId, List<Long> pIds) {
        QueryWrapper<EntityPersonnelInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("com_id", companyId);
        queryWrapper.in("p_id", pIds);
        return this.list(queryWrapper);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityPersonnelInfo> getEmptyFeaturePhoto(Long companyId) {
        return personnelInfo.getEmptyFeaturePhoto();
    }


}
